package com.dc.dbus.transport.netty.client;

import com.dc.dbus.transport.commons.ClientSideReceiver;
import com.dc.dbus.transport.netty.Log;
import com.dc.dbus.transport.netty.MsgBack;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class NettyClientHandler extends SimpleChannelInboundHandler<Object> {
	
	protected final ClientSideReceiver clientSideReceiver;
	protected final ClientChannelDisconnectHandler disconnectHandler;
	protected final NettyClient nettyClient;
	
	public NettyClientHandler(ClientSideReceiver clientSideReceiver,
			ClientChannelDisconnectHandler disconnectHandler, NettyClient nettyClient) {
		super();
		this.clientSideReceiver = clientSideReceiver;
		this.disconnectHandler = disconnectHandler;
		this.nettyClient = nettyClient;
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object response) throws Exception {
		
		if (Log.nettyLinkLogger.isDebugEnabled()) {
			Log.nettyLinkLogger.debug("NettyClientHandler.channelRead0: get response from server:" + ctx.channel().remoteAddress() + ":" + response);
		}
		
		MsgBack msgBack = (MsgBack) response;
		clientSideReceiver.handlerMsg(msgBack.replyForMsgId, msgBack.replyForCmd, msgBack.resultCode, msgBack.getParam());
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
	}
	
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {

		Log.nettyLinkLogger.warn("NettyClientHandler.channelInactive: disconect from server:" + ctx.channel().remoteAddress());
		
		disconnectHandler.channelDisconnect(nettyClient);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

		Log.nettyLinkLogger.warn("NettyClientHandler.exceptionCaught: netty client to server:" + ctx.channel().remoteAddress() + " exception");
	}

}